package com.wlz.learnjuc.lock;

import java.util.Random;

/**
 * 编写代码, 实现多线程数组求和.
 * 给定一个很长的数组 (长度 1000w), 通过随机数的方式生成 1-100 之间的整数.
 * 实现代码, 能够创建两个线程, 对这个数组的所有元素求和.
 * 其中线程1 计算偶数下标元素的和, 线程2 计算奇数下标元素的和.
 * 最终再汇总两个和, 进行相加
 * 记录程序的执行时间.
 */

class SumThread implements Runnable{
//    final int ARRAY_LENGTN = 10;
//    int[] arrs = new int[ARRAY_LENGTN];
    int start;
    int end;
    int sum;
    int[] arrs;

    public SumThread() {
    }

    public SumThread(int start, int even,int[] arrs) {
        this.start = start;
        this.end = end;
        this.arrs = arrs;
    }

    @Override
    public void run() {
        for (int i = start; i < end; i+=2) {
            sum += arrs[i];
        }
    }
    public int getSum(){
        return sum;
    }
    public void setSum(int sum){
        this.sum = sum;
    }
}
public class Test13 {
    public static void main(String[] args) throws InterruptedException {
        final int ARRAY_LENGTN = 10000000;
        int[] arrs = {1,2,3,4,5,6};
//        int[] arrs = new int[ARRAY_LENGTN];
//        int start = 0;
//        int odd = 0;
        for (int i = 0; i < s1.arrs.length; i++) {
            s1.arrs[i] = random.nextInt();
        }
        SumThread s1 = new SumThread(0,arrs.length,arrs);
        SumThread s2 = new SumThread(1,arrs.length,arrs);
        Random random = new Random();

        Thread t1 = new Thread(s1);
        Thread t2 = new Thread(s2);
        System.out.println();
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(s1.getSum()+" " + s2.getSum());
    }
}